﻿using System;
using System.Text;
using System.Windows.Forms;
using Tp.GUI.Base;
using Tp.Base;
using TpBaseObjects.Objects;
using TpData.Manager;
using TpTools;
using Tp.Properties;
using TpExtensions;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using TpContracts;

namespace Tp.GUI.Dialog {
    public partial class Angebot : TpBase {

        #region Members

        private string betreff = "Angebot";
        private List<Beilage> beilagen;
        private List<Person> mailCC;
        private List<Person> mailCCOutput;
        private bool setBeilagen = true;
        private const string errType = "Err";
        private const string logType = "Log";
        private const string logArea = "Tp.GUI.Dialog.Angebot";

        #endregion

        #region Constructors

        public Angebot() {
            InitializeComponent();
        }

        public Angebot(string orgName, string suchbegriff)
            : this() {
            eventHandler.Changed += SetSelectEmpfänger;
            eventHandler.AfterSelected += SetVersand;
            Cancel = true;

            SetAngebot(orgName, suchbegriff);

        }

        public Angebot(string OrgName, string suchbegriff, string betreff)
            : this(OrgName, suchbegriff) {
            this.betreff = betreff;
        }

        public Angebot(string orgName, string suchBegriff, Extensions.tpWindowType tpWindow)
            : this(orgName, suchBegriff) {
            switch (tpWindow) {
                case Extensions.tpWindowType.Mahnung:
                    this.tabAuswahl.TabPages.Remove(this.tpBeilagen);
                    this.tabAuswahl.TabPages.Remove(this.tpBetreff);
                    this.betreff = "Zahlungserinnerung";
                    this.Text = "Mahnung";
                    break;
                case Extensions.tpWindowType.Auftragsbestätigung:
                    this.betreff = "Auftragsbestätigung";
                    this.tabAuswahl.TabPages.Remove(this.tpMahnung);
                    break;
                case Extensions.tpWindowType.Korrepondenz:
                case Extensions.tpWindowType.Mail:
                    this.setBeilagen = false;
                    this.tabAuswahl.TabPages.Remove(this.tpMahnung);
                    this.betreff = "";
                    this.txtBetreff.Text = "";
                    break;
                default:
                    this.tabAuswahl.TabPages.Remove(this.tpMahnung);
                    break;
            }
        }


        #endregion

        #region Properties

        public bool Cancel {
            get;
            set;
        }

        public string SelectedType {
            get { return this.selectedType; }
            set { this.selectedType = value; }
        }

        public int Versand {
            get { return this.versand; }
            set { this.versand = value; }
        }

        public Recipient MyRecipient {
            get { return this.myRecipient; }
        }

        public List<Beilage> Beilagen {
            get { return this.beilagen; }
        }

        public List<Person> MailCC {
            get { return this.mailCCOutput; }
        }

        #endregion

        #region Events

        private void Angebot_Load(object sender, EventArgs e) {
            this.rbHerr.Checked = true;
            this.txtBetreff.Text = betreff;
            this.chkZuHanden.Enabled = false;
            this.rbMail.Checked = true;
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e) {
            SetDataBeforeClose();
            this.Close();
        }

        private void dgEmpfänger_CellClick(object sender, DataGridViewCellEventArgs e) {
            eventHandler.ChangeSelect(sender, e);
        }

        private void dgPerson_CellClick(object sender, DataGridViewCellEventArgs e) {
            eventHandler.ChangeSelect(sender, e);
        }

        private void gbVersand_Validated(object sender, EventArgs e) {
            //eventHandler.SelectChanged(sender, e);
        }

        private void rbBrief_CheckedChanged(object sender, EventArgs e) {
            GlobalVar.Versand = (int)GlobalVar.VersandArt.Mail;
            eventHandler.SelectChanged(sender, e);
        }

        private void rbFax_CheckedChanged(object sender, EventArgs e) {
            GlobalVar.Versand = (int)GlobalVar.VersandArt.Fax;
            eventHandler.SelectChanged(sender, e);
        }

        private void rbMail_CheckedChanged(object sender, EventArgs e) {
            GlobalVar.Versand = (int)GlobalVar.VersandArt.Brief;
            eventHandler.SelectChanged(sender, e);
        }

        private void chkZuHanden_CheckedChanged(object sender, EventArgs e) {
            eventHandler.SelectChanged(sender, e);
        }

        private void rbHerr_CheckedChanged(object sender, EventArgs e) {
            eventHandler.SelectChanged(sender, e);
        }

        private void rbFrau_CheckedChanged(object sender, EventArgs e) {
            eventHandler.SelectChanged(sender, e);
        }

        #endregion

        #region Public Methods

        public void SetAkontoDatasource(List<AkontoObj> akontos) {
            this.bsAkontos.DataSource = akontos;
        }

        public void SetInvoicesDatasource(List<InvoiceObj> dsInvoice) {
            this.bsRechnungen.DataSource = dsInvoice;
        }

        public void SetPaymentDatasource(List<AkontoObj> dsPayment) {
            this.bsZahlungen.DataSource = dsPayment;
        }

        public void SetReminderDatasource(List<MahnungObj> dsReminder) {
            this.bsMahnungen.DataSource = dsReminder;
        }

        #endregion

        #region Methods

        private void btnAddBeilage(object sender, EventArgs e) {
            try {
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK) {
                    string fileBezeichnung = InputBox.ShowDialog("Dateibezeichnung", "Beilage");

                    Beilage bel = new Beilage();
                    bel.FullFileName = openFileDialog1.FileName;
                    bel.IsChecked = true;
                    if (fileBezeichnung != null && fileBezeichnung.Length > 0) {
                        bel.BeilagenText = fileBezeichnung + " (" + bel.FileName + ")";
                    } else {
                        bel.BeilagenText = bel.FileName;
                    }
                    this.beilagenBindingSource.Add(bel);
                }
            } catch (Exception ex) {
                MessageBox.Show("Error" + ex.Message);
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, ex.Message, true);
            }
        }

        private void SetAngebot(string orgName, string suchbegriff) {
            //DataGridViewButtonColumn addFileName = new DataGridViewButtonColumn();
            //addFileName.Name = "Auswahl";
            //addFileName.Text = "Datei...";
            //addFileName.Width = 60;

            //this.dgBeilagen.Columns.Add(addFileName);
            //this.dgBeilagen.CellClick += new DataGridViewCellEventHandler(btnAddBeilage);

            Organisation org = OrganisationDataManager.LoadOrganisation(orgName, suchbegriff);
            if (org != null) {
                organisationBindingSource.DataSource = org;
                personBindingSource.DataSource = org.MyPersons;
                IEnumerable<Person> t1 = from t2 in org.MyPersons
                                         where t2.EMail != null
                                         select t2;

                SetMailCC();
                foreach (Person pers in t1) {
                    this.mailCC.Add(pers);
                }
                mailPersonCopyBindingSource.DataSource = this.mailCC;
            } else {
                string msg = String.Format(Resources.NameInDbNichtGefunden, OrgName, suchbegriff);
                MessageBox.Show(msg, "Dialoag Auswahl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cancel = true;
                this.Close();
            }

            SetBeilagen();
            beilagenBindingSource.DataSource = this.beilagen;
        }

        private void SetBeilagen() {

            if (this.setBeilagen) {
                if (Settings.Default.BeilagenFile1 != null && Settings.Default.BeilagenFile1.Length > 0) {
                    Beilage std = new Beilage();
                    std.FullFileName = Settings.Default.BeilagenFile1;
                    std.BeilagenText = Settings.Default.BeilagenFile1Text + " (" + std.FileName + ")";
                    std.IsChecked = true;
                    this.beilagen = new List<Beilage>();
                    this.beilagen.Add(std);
                }

                if (Settings.Default.BeilagenFile2 != null && Settings.Default.BeilagenFile2.Length > 0) {
                    Beilage std = new Beilage();
                    std.FullFileName = Settings.Default.BeilagenFile2;
                    std.BeilagenText = Settings.Default.BeilagenFile2Text + " (" + std.FileName + ")";
                    std.IsChecked = true;
                    if (this.beilagen != null) {
                        this.beilagen = new List<Beilage>();
                    }
                    this.beilagen.Add(std);
                }

                if (Settings.Default.BeilagenFile3 != null && Settings.Default.BeilagenFile3.Length > 0) {
                    Beilage std = new Beilage();
                    std.FullFileName = Settings.Default.BeilagenFile3;
                    std.BeilagenText = Settings.Default.BeilagenFile3Text + " (" + std.FileName + ")";
                    std.IsChecked = true;
                    if (this.beilagen != null) {
                        this.beilagen = new List<Beilage>();
                    }
                    this.beilagen.Add(std);
                }
            }
            
        }

        private void SetBeilagenData() {
            foreach (Beilage bel in this.beilagen) {
                if (!bel.IsChecked) {
                    this.beilagen.Remove(bel);
                    if (this.beilagen.Count == 0) {
                        break;
                    }
                }
            }
        }

        private void SetBetreff(string text, bool addText) {
            text = " " + text;
            string newText = this.txtBetreff.Text;
            if (addText) {
                newText += text;
            } else {
                newText = newText.Replace(text, "");
            }
            this.txtBetreff.Text = newText;
        }

        private void SetMailCC() {
            this.mailCC = new List<Person>();
        }

        private void SetMailCCData() {
            this.mailCCOutput = new List<Person>();
            foreach (Person mpc in this.mailCC) {
                if (mpc.SendToThisPerson) {
                    this.mailCCOutput.Add(mpc);
                }
            }

        }

        private void SetSelectEmpfänger(object sender, EventArgs e) {
            StringBuilder txt = new StringBuilder();
            DataGridView dgv = sender as DataGridView;
            DataGridViewRow row = dgv.CurrentRow;

            if (dgv.Tag.ToString() == "Org") {
                SelectedType = "Org";
                this.chkZuHanden.Checked = false;
                this.chkZuHanden.Enabled = false;
            }
            if (dgv.Tag.ToString() == "Person") {
                SelectedType = "Person";
                this.chkZuHanden.Enabled = true;
            }
            txt.Append(GetSelectedText());
            this.txtAuswahl.Text = txt.ToString();
        }

        private void SetVersand(object sender, EventArgs e) {
            StringBuilder txt = new StringBuilder();
            txt.Append(GetSelectedText());
            this.txtAuswahl.Text = txt.ToString();
        }

        private void SetRecipientData() {
            Organisation org = GlobalVar.currentOrganisation;
            Person pers = GlobalVar.currentPerson;

            if (SelectedType == "Org") {
                if (betreff == "AngebotOld") {
                    myRecipient.Anrede = Resources.Anrede + (rbFrau.Checked ? " " + Resources.Frau : " " + Resources.Herr).AddSpace() + org.OrgName;
                } else {
                    myRecipient.Anrede = (rbFrau.Checked ? Resources.Frau : Resources.Herr).AddSpace() + org.Prefix.AddSpace() + org.OrgName;
                }
                myRecipient.Name = org.Prefix.AddSpace() + org.OrgName.AddSpace() + org.RechtsForm;
                myRecipient.Straße = org.Straße;
                myRecipient.PlzOrt = org.Plz.ToString().AddSpace() + org.Ort;
                myRecipient.EMail = org.EMail;
                myRecipient.Fax = org.FaxNr;
            }

            if (SelectedType == "Person") {
                if (betreff == "AngebotOld") {
                    myRecipient.Anrede = Resources.Anrede + (pers.Geschlecht == 2 ? " " + Resources.Frau : Resources.AnredeErgänzungHerr + Resources.Herr).AddSpace() + Office.GetTitelName(pers.Titel1Key).AddSpace() + pers.Zuname;
                } else {
                    myRecipient.Anrede = (pers.Geschlecht == 2 ? Resources.Frau : Resources.Herr).AddSpace() + Office.GetTitelName(pers.Titel1Key).AddSpace() + pers.Zuname;
                }
                if (this.chkZuHanden.Checked) {
                    myRecipient.Name = ((string)org.Prefix.AddSpace() + org.OrgName.AddSpace() + org.RechtsForm).Trim();
                    myRecipient.ZuHanden = (pers.Geschlecht == 1 ? Resources.Herrn.AddSpace() : Resources.Frau.AddSpace()) + Office.GetTitelName(pers.Titel1Key).AddSpace() + pers.Vorname.AddSpace() + pers.Zuname;
                } else {
                    myRecipient.Name = Office.GetTitelName(pers.Titel1Key).AddSpace() + pers.Vorname.AddSpace() + pers.Zuname;
                }
                PlzOrt pl = CommonDataManager.LoadPlzOrt(pers.EPLZ);
                myRecipient.Straße = (pers.Straße == null | pers.Straße == string.Empty ? org.Straße : pers.Straße);
                myRecipient.PlzOrt = (pl.Plz == null | pl.Plz == string.Empty ? org.Plz.ToString() + " " + org.Ort : pl.Plz + " " + pl.Ort);
                myRecipient.EMail = (pers.EMail == null | pers.EMail == string.Empty ? org.EMail : pers.EMail);
                myRecipient.Fax = (pers.Fax == null | pers.Fax == string.Empty ? org.FaxNr : pers.Fax);
            }
            myRecipient.CheckZuHanden = this.chkZuHanden.Checked;
            myRecipient.Betreff = this.txtBetreff.Text;

            SetBeilagenData();
            SetMailCCData();
        }

        private void SetDataBeforeClose() {
            SetRecipientData();
            Cancel = false;
        }

        #endregion

        #region Functions

        private string GetSelectedText() {
            string ret = "";
            StringBuilder txt = new StringBuilder();

            if (SelectedType == "Org") {
                DataGridView dgv = this.dgEmpfänger;
                DataGridViewRow row = dgv.CurrentRow;
                Organisation org = row.DataBoundItem as Organisation;
                GlobalVar.currentOrganisation = org;
                if (this.rbHerr.Checked) {
                    txt.Append("Herr ");
                }
                if (this.rbFrau.Checked) {
                    txt.Append("Frau ");
                }
                txt.Append((org.Prefix ?? "").ToString() + " ");
                txt.Append((org.OrgName ?? "").ToString() + " ");
                if (this.rbMail.Checked) {
                    this.groupBox3.Enabled = true;
                    this.dgMailPersonKopie.Enabled = true;
                    Versand = (int)GlobalVar.VersandArt.Mail;
                    txt.Append("(" + (org.EMail ?? "").ToString() + ")");
                }
                if (this.rbFax.Checked) {
                    this.dgMailPersonKopie.Enabled = false;
                    this.groupBox3.Enabled = false;
                    Versand = (int)GlobalVar.VersandArt.Fax;
                    txt.Append("(" + (org.FaxNr ?? "").ToString() + ")");
                }
                if (this.rbBrief.Checked) {
                    this.dgMailPersonKopie.Enabled = false;
                    this.groupBox3.Enabled = false;
                    Versand = (int)GlobalVar.VersandArt.Brief;
                    txt.Append("(" + (org.Plz + " " + org.Ort + ", " + org.Straße ?? "").ToString() + ")");
                }
            }
            if (SelectedType == "Person") {
                DataGridView dgv = this.dgPerson;
                DataGridView dOrg = this.dgEmpfänger;
                DataGridViewRow row = dgv.CurrentRow;
                DataGridViewRow rowOrg = dOrg.CurrentRow;

                Person pers = row.DataBoundItem as Person;
                Organisation org = rowOrg.DataBoundItem as Organisation;

                GlobalVar.currentPerson = pers;
                PlzOrt pl = CommonDataManager.LoadPlzOrt(pers.EPLZ);
                if (pers.Geschlecht == 1) {
                    txt.Append("Herr ");
                }
                if (pers.Geschlecht == 2) {
                    txt.Append("Frau ");
                }
                txt.Append((pers.Vorname ?? "").ToString() + " ");
                txt.Append((pers.Zuname ?? "").ToString() + " ");
                if (this.rbMail.Checked) {
                    Versand = (int)GlobalVar.VersandArt.Mail;
                    txt.Append("(" + (pers.EMail ?? "").ToString() + ") ");
                }
                if (this.rbFax.Checked) {
                    Versand = (int)GlobalVar.VersandArt.Fax;
                    txt.Append("(" + (this.chkZuHanden.Checked ? (pers.Fax == null | pers.Fax == string.Empty ? org.FaxNr : pers.Fax) : pers.Fax) + ") ");
                }
                if (this.rbBrief.Checked) {
                    Versand = (int)GlobalVar.VersandArt.Brief;
                    txt.Append("(" + (this.chkZuHanden.Checked ? (org.Plz + " " + org.Ort + ", " + org.Straße ?? "").ToString() : (pl.Plz.AddSpace() + pl.Ort + ", " + pers.Straße ?? "").ToString()) + ") ");
                }
            }
            ret = txt.ToString();
            return ret;
        }

        #endregion

        #region Check - Events

        private void checkBox2_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox11_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox12_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox10_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox9_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox8_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox7_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e) {
            CheckBox chk = sender as CheckBox;
            SetBetreff(chk.Text, chk.Checked);
        }





        #endregion


    }
}
